<?php
/**
* @file $Id: Preferences.php 6 2006-06-23 23:14:35Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

if($_REQUEST['modfunc']!='backup')
	DrawHeader(ProgramTitle());

if(!$_REQUEST['system_tab'])
	$_REQUEST['system_tab'] = 'system';

if($_REQUEST['values'] && $_POST['values'])
{
	if($_REQUEST['system_tab']=='system')
	{
		$current_RET = DBGet(DBQuery("SELECT TITLE,VALUE FROM PROGRAM_CONFIG WHERE PROGRAM='".$_REQUEST['system_tab']."'"),array(),array('TITLE'));
	
		if($_REQUEST['system_tab']=='system')
		{
			if($_REQUEST['values'][$_REQUEST['system_tab']]['NAME_FORMAT']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['NAME_FORMAT'] = 'N';
			if($_REQUEST['values'][$_REQUEST['system_tab']]['WEIGHTS']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['WEIGHTS'] = 'N';
			if($_REQUEST['values'][$_REQUEST['system_tab']]['QUARTERS']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['QUARTERS'] = 'N';
			if($_REQUEST['values'][$_REQUEST['system_tab']]['BUS_ADDRESSES']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['BUS_ADDRESSES'] = 'N';
			if($_REQUEST['values'][$_REQUEST['system_tab']]['MAILING_ADDRESSES']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['MAILING_ADDRESSES'] = 'N';
			if($_REQUEST['values'][$_REQUEST['system_tab']]['WEIGHTED_GPA']!='Y')
				$_REQUEST['values'][$_REQUEST['system_tab']]['WEIGHTED_GPA'] = 'N';
		}

		if(true)
		{
			foreach($_REQUEST['values'] as $program=>$values)
			{
				foreach($values as $name=>$value)
				{
					if(!$current_RET[$name] && $value!='')
						DBQuery("INSERT INTO PROGRAM_CONFIG (PROGRAM,TITLE,VALUE) values('$program','$name','$value')");
					elseif($value!='')
						DBQuery("UPDATE PROGRAM_CONFIG SET VALUE='$value' WHERE PROGRAM='$program' AND TITLE='$name'");
					else
						DBQuery("DELETE FROM PROGRAM_CONFIG WHERE PROGRAM='$program' AND TITLE='$name'");
				}
			}
		}

		// So SystemPreferences() will get the new values
		unset($_FOCUS['SystemPreferences']);
	}
	elseif($_REQUEST['system_tab']=='default_user')
	{
		if(true)
		{
			$current_RET = DBGet(DBQuery("SELECT TITLE,VALUE,PROGRAM FROM PROGRAM_CONFIG WHERE PROGRAM IN ('Preferences','StudentFieldsSearch','StudentFieldsView') "),array(),array('PROGRAM','TITLE'));
		
			if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['SEARCH']!='Y')
				$_REQUEST['values']['Preferences']['SEARCH'] = 'N';
			if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['DEFAULT_ALL_SCHOOLS']!='Y')
				$_REQUEST['values']['Preferences']['DEFAULT_ALL_SCHOOLS'] = 'N';
			if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['NAME_FORMAT']!='Y')
				$_REQUEST['values']['Preferences']['NAME_FORMAT'] = 'N';
			if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['DISPLAY_STUDENT_ID']!='Y')
				$_REQUEST['values']['Preferences']['DISPLAY_STUDENT_ID'] = 'N';
			if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['DISPLAY_GRADE']!='Y')
				$_REQUEST['values']['Preferences']['DISPLAY_GRADE'] = 'N';
	
			if($_REQUEST['tab']=='display_options' && $_REQUEST['values']['Preferences']['HIDDEN']!='Y')
				$_REQUEST['values']['Preferences']['HIDDEN'] = 'N';
		
			if($_REQUEST['tab']=='student_fields')
			{
				DBQuery("DELETE FROM PROGRAM_CONFIG WHERE PROGRAM IN ('StudentFieldsSearch','StudentFieldsView')");
	
				foreach($_REQUEST['values'] as $program=>$values)
				{
					foreach($values as $name=>$value)
					{
						if(isset($value))
							DBQuery("INSERT INTO PROGRAM_CONFIG (PROGRAM,TITLE,VALUE) values('$program','$name','$value')");
					}
				}
			}
			else
			{
				foreach($_REQUEST['values'] as $program=>$values)
				{
					foreach($values as $name=>$value)
					{
						if(!$current_RET[$program][$name] && $value!='')
							DBQuery("INSERT INTO PROGRAM_CONFIG (PROGRAM,TITLE,VALUE) values('$program','$name','$value')");
						elseif($value!='')
							DBQuery("UPDATE PROGRAM_CONFIG SET VALUE='$value' WHERE PROGRAM='$program' AND TITLE='$name'");
						else
							DBQuery("DELETE FROM PROGRAM_CONFIG WHERE PROGRAM='$program' AND TITLE='$name'");
					}
				}
			}
	
			// So Preferences() will get the new values
			unset($_FOCUS['Preferences']);
		}
	}
	unset($_FOCUS['SystemPreferences']);
	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

if($_REQUEST['modfunc']=='backup' && $_REQUEST['_FOCUS_PDF']=='true')
{
	$str=""; 
	$ctype="application/force-download"; 
	header("Pragma: public"); 
	header("Expires: 0"); 
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	header("Cache-Control: public"); 
	header("Content-Description: File Transfer"); 
	header("Content-Type: $ctype"); 
	$header="Content-Disposition: attachment; filename=backup.sql;"; 
	header($header); 
	header("Content-Transfer-Encoding: binary"); 

	$res = DBQuery("select relname as tablename 
					from pg_class where relkind in ('r')
					and relname not like 'pg_%' and relname not like 'sql_%' order by tablename");
	
	while($row = pg_fetch_row($res)) 
	{
		$table = $row[0]; 
		$str .= "\n--\n"; 
		$str .= "-- Structure for table: '$table'"; 
		$str .= "\n--\n"; 
		$str .= "\nCREATE TABLE $table ("; 
		$res2 = DBQuery(" 
		SELECT  attnum,attname , typname , atttypmod-4 , attnotnull ,atthasdef ,adsrc AS def 
		FROM pg_attribute, pg_class, pg_type, pg_attrdef WHERE pg_class.oid=attrelid 
		AND pg_type.oid=atttypid AND attnum>0 AND pg_class.oid=adrelid AND adnum=attnum 
		AND atthasdef='t' AND lower(relname)='$table' UNION 
		SELECT attnum,attname , typname , atttypmod-4 , attnotnull , atthasdef ,'' AS def 
		FROM pg_attribute, pg_class, pg_type WHERE pg_class.oid=attrelid 
		AND pg_type.oid=atttypid AND attnum>0 AND atthasdef='f' AND lower(relname)='$table' ");                                              
		while($r = pg_fetch_row($res2)) 
		{ 
			$str .= "\n" . $r[1]. " " . $r[2]; 
			if($r[2]=="varchar") 
			{
				$str .= "(".$r[3] .")"; 
			} 
			if($r[4]=="t") 
			{
				$str .= " NOT NULL"; 
			} 
			if($r[5]=="t") 
			{
				$str .= " DEFAULT ".$r[6]; 
			}
			$str .= ","; 
		}
		$str=rtrim($str, ",");  
		$str .= "\n);\n"; 
		$str .= "\n--\n"; 
		$str .= "-- Creating data for '$table'"; 
		$str .= "\n--\n\n";

		$res3 = DBQuery("SELECT * FROM $table");
		while($r = pg_fetch_row($res3))
		{
			array_rwalk($r,'DBEscapeString');
			array_rwalk($r,'utf8_decode');
			$sql = "INSERT INTO $table VALUES ('";
			$sql .= implode("','",$r);
			$sql .= "');";
			$sql = ereg_replace("([,\(=])[\r\n\t ]*''",'\\1NULL',$sql);
			$str .= $sql;
			$str .= "\n";
			echo $str;
			$str = '';
		}

		 $res1 = DBQuery("SELECT pg_index.indisprimary, 
			pg_catalog.pg_get_indexdef(pg_index.indexrelid) 
		FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, 
			pg_catalog.pg_index AS pg_index 
		WHERE c.relname = '$table' 
			AND c.oid = pg_index.indrelid 
			AND pg_index.indexrelid = c2.oid"); 

		$str .= "\n\n--\n";
		$str .= "-- Creating indices for '$table'";
		$str .= "\n--\n\n";

		while($r = pg_fetch_row($res1))
		{
			$str .= $r[1].";\n";
		}
		$str .= "\n\n";
	}
	$res = DBQuery(" SELECT 
	cl.relname AS tabela,ct.conname, 
	pg_get_constraintdef(ct.oid) 
	FROM pg_catalog.pg_attribute a 
	JOIN pg_catalog.pg_class cl ON (a.attrelid = cl.oid AND cl.relkind = 'r') 
	JOIN pg_catalog.pg_namespace n ON (n.oid = cl.relnamespace) 
	JOIN pg_catalog.pg_constraint ct ON (a.attrelid = ct.conrelid AND 
	ct.confrelid != 0 AND ct.conkey[1] = a.attnum) 
	JOIN pg_catalog.pg_class clf ON (ct.confrelid = clf.oid AND clf.relkind = 'r') 
	JOIN pg_catalog.pg_namespace nf ON (nf.oid = clf.relnamespace) 
	JOIN pg_catalog.pg_attribute af ON (af.attrelid = ct.confrelid AND 
	af.attnum = ct.confkey[1]) order by cl.relname "); 
	
	while($row = pg_fetch_row($res)) 
	{
		$str .= "\n\n--\n"; 
		$str .= "-- Creating relationships for '".$row[0]."'"; 
		$str .= "\n--\n\n"; 
		$str .= "ALTER TABLE ONLY ".$row[0] . " ADD CONSTRAINT " . $row[1] . " " . $row[2] . ";"; 
	}        
	echo $str;

	$str = '';
	$res = DBQuery("select relname as tablename 
					from pg_class where relkind in ('S')
					and relname not like 'pg_%' and relname not like 'sql_%' order by tablename");
	
	while($row = pg_fetch_row($res))
	{
		$table = $row[0];
		$str .= "\n--\n"; 
		$str .= "-- Structure for sequence: '$table'"; 
		$str .= "\n--\n"; 
		$str .= "\nCREATE SEQUENCE $table INCREMENT 1 START ";

		$res2 = DBGet(DBQuery("SELECT last_value FROM public.$table"));
		$str .= ($res2[1]['LAST_VALUE']+1).';';
	}
	
	echo $str;
	echo "\n\n";
	exit;
}

unset($_REQUEST['search_modfunc']);
unset($_SESSION['_REQUEST_vars']['search_modfunc']);

if(!$_REQUEST['modfunc'])
{
	$current_RET = DBGet(DBQuery("SELECT TITLE,VALUE FROM PROGRAM_CONFIG WHERE PROGRAM='".$_REQUEST['system_tab']."'"),array(),array('TITLE'));
	
	if($_REQUEST['system_tab']!='database_backup')
	{
		echo "<FORM action=Modules.php?modname=$_REQUEST[modname]&amp;system_tab=$_REQUEST[system_tab]&amp;tab=$_REQUEST[tab] method=POST>";
	
		DrawHeader('','<INPUT type=submit value='._('Save').'>');
	}
	echo '<BR>';

	$tabs = array(array('title'=>_('General'),'link'=>"Modules.php?modname=$_REQUEST[modname]&amp;system_tab=system"),
					array('title'=>_('Default User Preferences'),'link'=>"Modules.php?modname=$_REQUEST[modname]&amp;system_tab=default_user"),
					array('title'=>_('Database Backup'),'link'=>"Modules.php?modname=$_REQUEST[modname]&amp;system_tab=database_backup")
				);
//					array('title'=>_('Default Gradebook Configuration'),'link'=>"Modules.php?modname=$_REQUEST[modname]&amp;system_tab=default_gradebook")				

	$_FOCUS['selected_tab'] = "Modules.php?modname=$_REQUEST[modname]&amp;system_tab=".$_REQUEST['system_tab'];
	PopTable('header',$tabs);

	if($_REQUEST['system_tab']!='default_user')
	echo '<fieldset>';
	
	if($_REQUEST['system_tab']=='system')
	{
		echo '<TABLE>';
		$options = '';
		for($i=0;$i<=20;$i++)
		{
			if(SystemPreferences('PAST_ATTENDANCE_DAYS')==$i)
				$selected = ' SELECTED';
			else
				$selected = '';
			$options .= '<OPTION value='.$i.$selected.'>'.$i.' ';
			if($i==1)
				$options .= _('day');
			else
				$options .= _('days');
		}
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Allow teachers to modify<BR>the previous days\' attendance').'</TD><TD><SELECT name=values[system][PAST_ATTENDANCE_DAYS]>'.$options.'</SELECT></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('User Authentication').'</TD><TD><INPUT type=radio name=values[system][AUTHENTICATION] value="db"'.((SystemPreferences('AUTHENTICATION')=='db')?' CHECKED':'').'>'._('Focus/SIS Database').'<INPUT type=radio name=values[system][AUTHENTICATION] value=ldap'.((SystemPreferences('AUTHENTICATION')=='ldap')?' CHECKED':'').'>'._('LDAP Directory Server').'</TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Report Card Codes').'</TD><TD><INPUT type=radio name=values[system][REPORT_CARD] value="both"'.((SystemPreferences('REPORT_CARD')=='both')?' CHECKED':'').'>'._('Percent & Letter Grade').'<INPUT type=radio name=values[system][REPORT_CARD] value=grade'.((SystemPreferences('REPORT_CARD')=='grade')?' CHECKED':'').'>'._('Letter Grade').'<INPUT type=radio name=values[system][REPORT_CARD] value=percent'.((SystemPreferences('REPORT_CARD')=='percent')?' CHECKED':'').'>'._('Percent').'</TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Default Credits').'</TD><TD><INPUT type=text name=values[system][DEFAULT_CREDITS] value="'.SystemPreferences('DEFAULT_CREDITS').'" maxlength=10 size=2></TD></TR>';
		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][WEIGHTED_GPA] value=Y'.((SystemPreferences('WEIGHTED_GPA')=='Y')?' CHECKED':'').'>'._('Use Weighted GPA').'<BR><BR></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('School Year Title').'</TD><TD><INPUT type=radio name=values[system][SYEAR_TITLE] value="YYYY-YYYY"'.((SystemPreferences('SYEAR_TITLE')=='YYYY-YYYY')?' CHECKED':'').'>'.UserSyear().'-'.(UserSyear()+1).'<INPUT type=radio name=values[system][SYEAR_TITLE] value=YYYY'.((SystemPreferences('SYEAR_TITLE')=='YYYY')?' CHECKED':'').'>'.UserSyear().'</TD></TR>';
		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][VARIABLE_PERIOD_LENGTH] value=Y'.((SystemPreferences('VARIABLE_PERIOD_LENGTH')=='Y')?' CHECKED':'').'>'._('Period Lengths vary by day of the week').'<BR><BR></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Decimal Point Character').'</TD><TD><INPUT type=radio name=values[system][DECIMAL] value="."'.((SystemPreferences('DECIMAL')=='.')?' CHECKED':'').'>Period (<b>.</b>)<INPUT type=radio name=values[system][DECIMAL] value=","'.((SystemPreferences('DECIMAL')==',')?' CHECKED':'').'>Comma (<b>,</b>)</TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Currency Symbol').'</TD><TD><INPUT type=text name=values[system][CURRENCY] value="'.SystemPreferences('CURRENCY').'" maxlength=1 size=1></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><BR><font color=gray>'._('Default City').'</TD><TD><BR><INPUT type=text name=values[system][DEFAULT_CITY] value="'.SystemPreferences('DEFAULT_CITY').'" maxlength=60 size=20></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Default State').'</TD><TD><INPUT type=text name=values[system][DEFAULT_STATE] value="'.SystemPreferences('DEFAULT_STATE').'" maxlength=10 size=2></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Default Zipcode').'</TD><TD><INPUT type=text name=values[system][DEFAULT_ZIPCODE] value="'.SystemPreferences('DEFAULT_ZIPCODE').'" maxlength=10 size=5></TD></TR>';
		echo '<TR><TD valign=top align='.ALIGN_RIGHT.'><font color=gray>'._('Default Area Code').'</TD><TD><INPUT type=text name=values[system][DEFAULT_AREACODE] value="'.SystemPreferences('DEFAULT_AREACODE').'" maxlength=10 size=4></TD></TR>';
//		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][WEIGHTS] value=Y'.((SystemPreferences('WEIGHTS')=='Y')?' CHECKED':'').'>'._('Use Course Weights').'</TD></TR>';
//		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][QUARTERS] value=Y'.((SystemPreferences('QUARTERS')=='Y')?' CHECKED':'').'>'._('Use Quarters').'</TD></TR>';
		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][BUS_ADDRESSES] value=Y'.((SystemPreferences('BUS_ADDRESSES')=='Y')?' CHECKED':'').'>'._('Use Bus Addresses').'</TD></TR>';
		echo '<TR><TD></TD><TD><INPUT type=checkbox name=values[system][MAILING_ADDRESSES] value=Y'.((SystemPreferences('MAILING_ADDRESSES')=='Y')?' CHECKED':'').'>'._('Use Mailing Addresses').'</TD></TR>';
		echo '</TABLE>';
	}
	elseif($_REQUEST['system_tab']=='default_user')
	{
		$old_preferences = $_FOCUS['Preferences'];
		foreach($_FOCUS['Preferences']['Preferences'] as $item=>$value)
			$_FOCUS['Preferences']['Preferences'][$item][1]['VALUE'] = SystemPreferences($item,'Preferences');
		/*
			foreach($_FOCUS['Preferences']['StudentFieldsSearch'] as $item=>$value)
				$_FOCUS['Preferences']['StudentFieldsSearch'][$item][1]['VALUE'] = SystemPreferences($item,'StudentFieldsSearch');
			foreach($_FOCUS['Preferences']['StudentFieldsView'] as $item=>$value)
				$_FOCUS['Preferences']['StudentFieldsView'][$item][1]['VALUE'] = SystemPreferences($item,'StudentFieldsView');
			unset($_FOCUS['Preferences']['StudentFieldsSearch']);
		*/
		include($staticpath.'modules/Users/Preferences.php');	
		$_FOCUS['Preferences'] = $old_preferences;
	}
	elseif($_REQUEST['system_tab']=='default_gradebook')
	{
		include($staticpath.'modules/Grades/Configuration.php');		
	}
	elseif($_REQUEST['system_tab']=='database_backup')
	{
		echo '<FORM action=Modules.php?modname='.$_REQUEST['modname'].'&modfunc=backup&_FOCUS_PDF=true method=POST>';
		echo _('Download backup files periodically in case of system failure.');
		echo '<BR><BR>';
		echo '<CENTER><INPUT type=submit value="'._('Download Backup File').'"></CENTER>';
		echo '</FORM>';
	}

	if($_REQUEST['system_tab']!='database_backup')
		echo '<BR><CENTER><INPUT type=submit value='._('Save').'></CENTER>';

	if($_REQUEST['system_tab']!='default_user')
		echo '</fieldset>';
	PopTable('footer');

	if($_REQUEST['system_tab']!='database_backup')
		echo '</FORM>';
}

?>